package helloworld;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        //使用ini配置文件 创建一个SecurityManager实例  不重要
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);
        //获取当前的subject，调用SecurityUtils.getSubject()
        Subject currentUser = SecurityUtils.getSubject();
        //测试使用session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("------------------------------------> session中的消息为： [" + value + "]");
        }

        //测试当前用户是否已经被认证，即是否已经被登录
        //调用subject的isAuthenticated()方法
        if (!currentUser.isAuthenticated()) {
            //把用户名密码封装为UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //后边在解释RememberMe
            token.setRememberMe(true);
            try {
                //执行登录操作
                currentUser.login(token);
            }
            //未知的账户 会抛出UnknownAccountException
            catch (UnknownAccountException uae) {
                log.info("-------------------------------->  未知的账户" + token.getPrincipal());
                return; 
            }
            //错误的密码 会抛出IncorrectCredentialsException
            catch (IncorrectCredentialsException ice) {
                log.info("------------------------------> 错误密码 " + token.getPrincipal() + " was incorrect!");
                return; 
            }
            //用户被锁定 spring集成后测试
            catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            //所有认证异常的父类
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        log.info("----------------------------->  登录成功！ [" + currentUser.getPrincipal() + "]");


        //测试是否有这个角色
        if (currentUser.hasRole("schwartz")) {
            log.info("----> 有这个角色");
        } else {
            log.info("----> 没有这个角色");
            return; 
        }

        //测试是否具备某个行为
        if (currentUser.isPermitted("lightsaber:weild")) {
            log.info("----> You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }


        if (currentUser.isPermitted("user:delete:zhangsan")) {
            log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        System.out.println("---->" + currentUser.isAuthenticated());
        
        currentUser.logout();
        
        System.out.println("---->" + currentUser.isAuthenticated());

        System.exit(0);
    }
}
